<?php
class ss_dao_entry extends ss_dao_object{
	
	public function master(){
		//ss_error::log('Master');
		$result=array('identry'=>$this->primary(),'$ref'=>$this->primary());
		foreach(array('headline','slug','date_pub','teaser','catdata') as $val){
			$result[$val]=$this->{$val}();
		}
		return $result;
		/*return array(
			'headline'=>$this->headline(),
			'slug'=>$this->slug(),
			'$ref'=>$this->primary(),'identry'=>$this->primary(),'date_pub'=>$this->date_pub(),);*/
	}
	
	public function detail(){
		return array_merge(array('catdata'=>$this->catdata()),$this->getData());
		return $this->getData();
	}
	
	public function active($val=null){
		if(!is_null($val)) $this->active=($val?1:0);
		return ($this->active?true:false);
	}
	
	public function timedpub($val=null){
		if(!is_null($val)) $this->timedpub=($val?1:0);
		return ($this->timedpub?true:false);
	}
	
	public function catidlist($list=null){
		//ss_error::log($list,'Catidlist');
		if(is_array($list)) $this->catidlist=implode(',',$list);
		return explode(',',trim($this->catidlist));
	}
	
	public function catsluglist($list=null){
		//ss_error::log($list,'Catslug');
		if(is_array($list)) $this->catsluglist=implode(',',$list);
		return explode(',',trim($this->catsluglist));
	}
	
	public function catnamelist($list=null){
		if(is_array($list)) $this->catnamelist=implode(',',$list);
		return explode(',',$this->catnamelist);
	}
	
	public function date_create($date=null){
		if($date) $this->date_create=$this->dateToMysql($date);
		return $this->date_create;
	}
	
	public function date_mod($date=null){
		if($date) $this->date_mod=$this->dateToMysql($date);
		return $this->date_mod;
	}
	
	public function date_pub($date=null){
		if($date) $this->date_pub=$this->dateToMysql($date);
		return $this->date_pub;
	}
	
	public function date_rej($date=null){
		if($date) $this->date_rej=$this->dateToMysql($date);
		return $this->date_rej;
	}
	
	private function setArray($name,$val=null){
		if(!is_null($val)) {
			if(is_array($val)) $val=implode(',',$val);
			$this->attributes[$name]=$val;
		}
		return explode(',',$this->attributes[$name]);
	}
	
	public function catdata(){
		return array(
			'id'=>$this->catidlist(),
			'slug'=>$this->catsluglist(),
			'name'=>$this->catnamelist());
	}
}

class ss_dao_entry_mapper extends ss_dao_mapper{
	protected $table='entry';
	protected $primary='identry';
	protected $location=array(
		'entry'=>Array(
			'identry','active','timedpub','headline','name','slug','teaser','text','date_create','date_mod','date_pub','date_rej','lang_idlang','user_iduser_create','user_iduser_modify','image_idimage'
		),
		'entry_has_category'=>array(
			'catidlist','catnamelist','catsluglist'
		),
		'entry_has_staff'=>array(
			'staffidlist','staffnamelist','staffsluglist'
		)
	);
	
	public function api_master($query=null){
		$q=$this->injector->create('ss_dao_query');
		$sql=$q
		->from(array(
			'api_entry'))
		->where(array($query))
		->select();
		$stmt=$this->da->runStmt($sql,$q->values());
		return $this->getArray($stmt);
	}
	
	public function master($query=null){
		$q=$this->injector->create('ss_dao_query');
		$sql=$q
		->from(array(
			'ss_entry'))
		->where(array($query))
		->select();
		$stmt=$this->da->runStmt($sql,$q->values());
		return $this->getArray($stmt);
	}
	
	public function api_detail($id){
		$q=$this->injector->create('ss_dao_query');
		$sql=$q
		->from(array(
			'api_entry'))
		->where(array(
			array($this->primary=>$id))
			)
		->select();
		$stmt=$this->da->runStmt($sql,$q->values());
		return $stmt->fetchObject('ss_dao_entry',array($this->primary));
	}
	
	/*public function getEntries($lnum=10,$lstart=0){
		$query=$this->injector->create('ss_dao_query');
		$sql=$query
		->from(array(
			'getentry'))
		->where(array(
			array(
				'lft'=>'date_rej',
				'cmp'=>'IS',
				'rgt'=>array('com'=>'NULL')
			),
			array(
				'ar'=>'OR',
				'lft'=>'date_rej',
				'cmp'=>'>',
				'rgt'=>array('com'=>'NOW()')
				)))
		->limit($lnum,$lstart)
		->select();
		$stmt=$this->da->runStmt($sql,$query->values());
		//$stmt=$this->da->prepare($sql);
		//$this->da->execute($stmt,$query->values());
		return $this->getArray($stmt);
	}*/
	
	public function getEntryBySlug($slug){
		$query=$this->injector->create('ss_dao_query');
		$sql=$query
		->from(array(
			'ss_entry'))
		->where(array(
			array(
				'slug'=>':slug'
				)))
		->select();
		$stmt=$this->da->query("SELECT * FROM `ss_entry` WHERE slug = '{$slug}'");
		$result=$stmt->fetchObject('ss_dao_entry',array($this->primary));
		$this->da->closeCursor($stmt);
		return $result;
	}
	
	public function getEntriesByCategorySlug($slug,$active=true,$lnum=10,$lstart=null){
		$sql='CALL getEntriesByCategorySlug(:catslug,:active,:lnum,:lstart);';
		$stmt=$this->da->runStmt($sql,array(':catslug'=>$slug,':active'=>$active,':lnum'=>$lnum,':lstart'=>$lstart));
		return $this->getArray($stmt);
	}
	
	public function getEntryByStructure($idstructure,$lnum=10,$lstart=NULL){
		$q=$this->injector->create('ss_dao_query');
		$sql=$q
		->from(array(
			'ss_entrybystucture'))
		->where(array(
			array(
				'idstructure'=>$idstructure
				)))
		->select();
		$stmt=$this->da->runStmt($sql,$q->values());
		return $this->getArray($stmt);
		//$stmt=$this->da->query("SELECT * FROM `getentry` WHERE slug = '{$slug}'");
		$result=$stmt->fetchObject('ss_dao_entry',array($this->primary));
		$this->da->closeCursor($stmt);
		return $result;
		/*$id=(($struct instanceof hamilton_dao_node)?$struct->primary():$struct);
		$sql='CALL getEntriesByStructure(:idstructure,:lnum,:lstart);';
		$stmt=$this->da->runStmt($sql,array(':idstructure'=>$id,':lnum'=>$lnum,':lstart'=>$lstart));
		return $this->getArray($stmt);*/
	}
	
	private function getArray($stmt){
		$result=array();
		while($obj=$stmt->fetchObject('ss_dao_entry',array($this->primary))){
			$result[$obj->{$this->primary}()]=$obj->clean();
		}
		$this->da->closeCursor($stmt);
		return $result;
	}
	/*
	public function query($query){
		return $this->master();
	}
	*/
	
	public function put($query,$body,$data){
		if($data->catidlist() != $body['catidlist']){
			$delCat=array_diff($data->catidlist(),$body['catidlist']);
			$addCat=array_diff($body['catidlist'],$data->catidlist());
			$del=$add=null;
			if(count($delCat)>0){
				$del=array(
				array(
					'lft'=>'entry_identry',
					'rgt'=>array('com'=>$data->primary())
					),
				array(
					'lft'=>'category_idcategory',
					'cmp'=>false,
					'rgt'=>array(
						'com'=>'IN('.implode(',',$delCat).')'
						)
					)
				);
			}
			if(count($addCat)>0){
				foreach($addCat as $val) $add[]=array('entry_identry'=>$data->primary(),'category_idcategory'=>$val);
			}
			$this->changeRelation('entry_has_category', $del, $add);
		}
		foreach($body as $key=>$val){
			if(!empty($key)) $data->{$key}($val);
		}
		$this->update($data);
		ss_error::log($data->changed());
	}
	
	public function post($query,$body){
		ss_error::log($body,'Body');
		$data=new ss_dao_entry($this->primary);
		$data->setAttributes($body);
		ss_error::log($data->getAttributes(),'Attributes');
		$data->catidlist($body['catidlist']);
		/*
		foreach($body as $key=>$val){
			if(!empty($key)) $data->{$key}($val);
		}*/
		//ss_error::log($data);
		/*
		if(count($data->catidlist())>0){
			$delCat=array_diff($data->catidlist(),$body['catidlist']);
			$addCat=array_diff($body['catidlist'],$data->catidlist());
			$del=$add=null;
			if(count($delCat)>0){
				$del=array(
				array(
					'lft'=>'entry_identry',
					'rgt'=>array('com'=>$data->primary())
					),
				array(
					'lft'=>'category_idcategory',
					'cmp'=>false,
					'rgt'=>array(
						'com'=>'IN('.implode(',',$delCat).')'
						)
					)
				);
			}
			if(count($addCat)>0){
				foreach($addCat as $val) $add[]=array('entry_identry'=>$data->primary(),'category_idcategory'=>$val);
			}
			$this->changeRelation('entry_has_category', $del, $add);
		}
		*/
		//ss_error::log($obj);
		$temp=$this->update($data);
		ss_error::log($temp);
		return  $temp;
		//$this->changeRelation('entry_has_category', $del, $add);
	}
	
	protected function setEntryCat($cat){
		ss_error::log($cat,'Setting categories to');
		$q=$this->injector->create('ss_dao_query');
			$sql=$q->from(array(
				'entry_has_category'))
			->where(array(
				//array('lft'=>'entry_identry','cmp'=>false,'rgt'=>array('com'=>'IN('.$cat.')')))
				array('lft'=>'entry_identry','rgt'=>array('com'=>'IN('.$cat.')')))
				)
			->delete();
		ss_error::log($sql);
		$this->da->exec($sql);
	}
	
	public function update(ss_dao_object_interface $obj){
		$result=array();
		$changed=array();
		foreach($obj->changed() as $val) $changed[$val]=$obj->{$val};
		if(count($changed)==0) return false;
		foreach($this->location['entry'] as $val){
			if(array_key_exists($val,$changed)) $result['entry'][$val]=$changed[$val];
		}
		foreach($this->location['entry_has_category'] as $val){
			if(array_key_exists($val,$changed)) $result['entry_has_category'][$val]=$changed[$val];
		}
		foreach($this->location['entry_has_staff'] as $val){
			if(array_key_exists($val,$changed)) $result['entry_has_staff'][$val]=$changed[$val];
		}
		ss_error::log($result,'Changed data queue');
		if(isset($result['entry'])){
			//ss_error::log($result['entry'],'Changed data entry');
			//if(!$obj->{$this->primary}) return $this->insert($obj);
			$q=$this->injector->create('ss_dao_query');
			$q->from(array(
				$this->table))
				->set(array($result['entry']));
			if(!$obj->{$this->primary}){
				$sql=$q->insert();
				$stmt=$this->da->runStmt($sql,$q->values());
				$obj->{$this->primary}=$this->da->lastInsertId();
				return $obj;
			} else {
				$sql=$q->where(array(
				array($this->primary=>$obj->{$this->primary}))
				)->update();
				$stmt=$this->da->runStmt($sql,$q->values());
			}
			/*ss_error::log($sql);
			ss_error::log($q->values());
			$stmt=$this->da->runStmt($sql,$q->values());*/
		}
		return $obj;
		//if(isset($result['entry_has_category'])) $this->setEntryCat($obj);
		//return false;
	}
}
?>